<?php
/**
 * Clase para enviar mail utilizando Stomp.
 *
 * En un principio esta clase estaba basada en Basado en Me_Apis_Queue de code y usaba la libreria Stomp
 * Ahora voy a cambiar la implementacion para basar esta clase en Zend_Queue, o sea esta clase quedaria por backward-compatibility.
 * Adji (12/08/2009).
 *
 */
class Ext_Queue
{
    // default read timeout set to 2 seconds
    const TIMEOUT_SEC		= 2;

    private $_lastMessage = null;
    private $_timeout;
    private $_queue;


    public function __construct ($brokerUri, $destinationQueue, $ack = 'client')
    {
    	//Ext_Debug::dump(parse_url( $brokerUri ) );exit;
        // bool  isQueueInDinctionary($queue);
        // @todo: reveer esto.
        $options = array();
        $options[ 'driverOptions' ] = parse_url( $brokerUri );
        $options[ 'driverOptions' ][ 'timeout_sec' ] = self::TIMEOUT_SEC;
        $options[ 'driverOptions' ][ 'username' ] = ( isset( $options[ 'user' ]))?$options[ 'user' ]:null;
        $options[ 'name' ] = $destinationQueue;
        $this->_queue = new Zend_Queue( 'Activemq',  $options );
    }
    /**
     * Envia mensajes a la cola.
     *
     * @param string $message
     * @return mixed Zend_Message
     */
    public function enqueue ($message_body, $message_properties = null)
    {
        return $this->_queue->send( $message_body );
    }

    /**
     * Lee un mensaje de una cola
     *
     * @return void
     */
    public function dequeue ()
    {
        $messages = $this->_queue->receive( 1, $this->_timeout );
        $this->_lastMessage = $messages[ 0 ];
        return $this->_lastMessage->body;
    }


    public function ackMessage ()
    {
        if ( $this->_lastMessage != null ) {
            $this->_queue->deleteMessage( $this->_lastMessage );
            $this->_lastMessage = null;
        }
    }

    public function getAckMode ()
    {
        throw new Exception( 'get/setAckMode unimplemented');
    }

    public function setAckMode ($ack_mode)
    {
        throw new Exception( 'get/setAckMode unimplemented');
    }

    public function setReadTimeout( $sec ) {
        $this->_timeout = $sec;
    }
}


